<?php
namespace app\user\event\listeners\user;

use app\user\logic\user\Credit as CreditLogic;
use app\user\logic\user\CreditFlow;
use app\course\logic\base\Course;

/**
 * 购买课程产生的积分
 */
class CourseCredit
{
    public static function handle($param)
    {
        // 参数
        $key = $param['course_id'];
        $mid = $param['user_id'];
        $rel = $param['rel_pk'];
        $type = $param['type']??"";

        if ( !$mid ) return;
        // 课程积分
        $course = app(Course::class)->findOrEmpty($key);

        if ( $course->isEmpty() ) return;

        $title = $course->title ? : '**';
        switch ($type) {
            case 'purchase':
                $score = $course->give_credit;
                $note = '购买课程《' . $title .  '》获得的积分';
                break;
            
            case 'share':
                $score = $course->share_credit;
                $note = '分享课程《' . $title .  '》获得的积分';
                break;
            
            case 'comment':
                $score = $course->comment_credit;
                $note = '评论课程《' . $title .  '》获得的积分';
                break;
            
            default:
                $score = $course->give_credit;
                $note = '购买课程《' . $title .  '》获得的积分';
                break;
        }

        if ( $score ) {
            // 添加积分
            $data = app(CreditLogic::class)->where('user_id', $mid)->findOrEmpty();

            if ( $data->isEmpty() ) {
            // 不存在就添加
                $data = CreditLogic::create([
                    'user_id' => $mid,
                    'credit'  => $score,
                ]);

                $re = $data->isEmpty() ? 0 : 1;
                $credit = $score;
            } else {
            // 存在就修改
                $data->credit  += $score;
                $re             = $data->save();
                $credit         = $data->credit;
            }

            if ( $re ) {
                // 添加流水
                $create = [
                    'user_id'   => $mid,
                    'type'      => 4,
                    'num'       => $score,
                    'credit'    => $credit,
                    'rel_type'  => 'course',
                    'rel_pk'    => $rel,
                    'note'      => $note,
                ];

                app(CreditFlow::class)::create($create);
            }
        }   
    }
}
